
<template>
  <div>
    <el-tree
      ref="refTree"
      :data="list"
      :props="{ label: 'name' }"
      check-strictly
      :show-checkbox="true"
      :default-expand-all="true"
      node-key="id"
    />
    <!-- 没有：就是字符串，加了就是布尔值 -->
    <el-button
      size="small"
      @click="hCancel"
    >取消</el-button>
    <el-button
      size="small"
      type="primary"
      @click="hSubmit"
    >确定</el-button>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    hCancel() {
      this.$emit('close-dialog')
      // 清空当前的选择
      this.$refs.refTree.setCheckedKeys([])
    },
    // 获取所有的权限
    async loadPermissionList() {
      // 发请求，获取权限列表
      const { data } = await getPermissionList()
      console.log('权限列表的数据是', data)
      this.list = tranListToTreeData(data)
    },
    // 获取现有的权限
    async loadRoleDetail() {
      const res = await getRoleDetail(this.roleId)
      // 回填
      this.$refs.refTree.setCheckedKeys(res.data.permIds)
    },
    async hSubmit() {
      // 从tree取出选中的id
      const permIds = this.$refs.refTree.getCheckedKeys()
      console.log('当前选中的节点数组是', permIds)
      const res = await assignPerm({ id: this.roleId, permIds })
      console.log('保存的权限', res)
      this.$message.success('保存成功')
      this.hCancel()
    }
  }
}
</script>

<style>

</style>
